﻿using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using System.Text;

namespace Infrastructure.Utils.Helpers
{
    /// <summary>
    /// 包含了与字符串压缩解压缩相关的一些常用扩展方法
    /// </summary>
    public static class CompressHelper
    {
        /// <summary>
        /// 压缩数据组
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static byte[] Compress(string source)
        {
            using (var ms = new System.IO.MemoryStream())
            {
                using (var gzip = new System.IO.Compression.GZipStream(ms, CompressionMode.Compress))
                {
                    using (var sw = new System.IO.StreamWriter(gzip, System.Text.Encoding.UTF8))
                    {
                        sw.Write(source);
                        sw.Close();
                        return ms.ToArray();
                    }
                }
            }
        }

        /// <summary>
        /// 解压缩数据组
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string Decompress(byte[] source)
        {
            using (var ms = new System.IO.MemoryStream(source))
            {
                using (var gzip = new System.IO.Compression.GZipStream(ms, CompressionMode.Decompress))
                {
                    using (var sr = new System.IO.StreamReader(gzip, System.Text.Encoding.UTF8, true))
                    {
                        return sr.ReadToEnd();
                    }
                }
            }
        }

        /// <summary>
        /// 解压缩数据组
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static byte[] DecompressToArray(this byte[] source)
        {
            using (var ms = new System.IO.MemoryStream(source))
            {
                using (var gzip = new System.IO.Compression.GZipStream(ms, CompressionMode.Decompress))
                {
                    using (var msout = new System.IO.MemoryStream())
                    {
                        var buffer = new byte[1024];
                        var count = 0;
                        while ((count = gzip.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            msout.Write(buffer, 0, count);
                        }
                        msout.Close();

                        return msout.ToArray();
                    }
                }
            }
        }

    }
}
